<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="nav">
    <a href="#/page1">page1</a>
    <a href="#/page2">page2</a>
    <a href="#/page3">page3</a>
</div>
<div id="container"></div>
  <script>
    class HashRouter {
      constructor() {
        this.routers = {}
        window.addEventListener('hashchange',this.load.bind(this))
      }
      // 注册路由 
      register(hash,callback = () => {}) {
        this.routers[hash] = callback
      }
      // 用于注册首页
      registerIndex(callback=function(){}){
        this.routers['index'] = callback
      }
      // 没有找到的回调函数
      registerNotFound(callback=function(){}) {
        this.routers['404'] = callback
      }
      registerError(callback=function(){}){
        this.routers['error'] = callback
      }
      // 调用回调函数
      load() {
        // 得到当前的哈希值
        let hash = location.hash.slice(1) //目的是为了去除#
        let handler = this.routers['index']
        hash && (handler = this.routers[hash])
        // 如果没有找到
        if(!handler) {
          handler = this.routers['404']
        }
        try {
          handler.call(this)
        } catch (error) {
          console.error(error)
          this.routers['error'].call(this)
        }
      }
    }
    let container = document.getElementById('container')
    let router = new HashRouter()
    router.registerIndex(function() {container.innerHTML = '我是首页'})
    router.register('/page1',function() {container.innerHTML = '我是page1'})
    router.register('/page2',function() {container.innerHTML = '我是page2'})
    router.register('/page3',function() {container.innerHTML = '我是page3'})
    router.register('/page4',function() {throw new Error('抛出一个错误')})
    router.registerNotFound(function() {container.innerHTML = '404 NOT Found'})
    router.registerError(function(){container.innerHTML = '出错啦！'})
    router.load()
    // window.addEventListener('hashchange',function() {
    //   // 变化时开始执行回调函数
    //   router.load()
    // })
  </script>
</body>
</html>